<template>
	<view class="dept-warp">
		<uni-data-picker 
			:placeholder="placeholder" 
			:popup-title="placeholder"
			:localdata="treeData"
			:map="{text:'deptName',value:'deptCode'}"
			:readonly="disabled"
			v-model="deptValue"
			@change="handleDept"
			:class="{disabled:disabled}"
		>
		</uni-data-picker>
	</view>
</template>

<script>
	import { getAction } from '@/api/manage.js'
	export default {
		name: 'DeptSelect',
		props: {
			value: String,
			placeholder:{
				type:String,
				default:'请选择'
			},
			disabled:Boolean
		},
		data() {
			return {
				treeData: [],
				urlObj:{
					list:'/dept/tree'
				},
				deptObj:{},
				deptValue:''
			}
		},
		watch: {
			value: {
				handler(val) {
					this.deptValue = val
				},
				deep:true,
				immediate:true
			}
		},
		methods: {
			initData() {
				getAction(this.urlObj.list).then(res => {
					if (res.data.success) {
						this.treeData = res.data.result			
						this.deptObj = {}
						this.toObj(this.treeData)
					}
				})
			},
			toObj(list){
				list.forEach(item => {
					this.deptObj[item.deptCode] = { ...item }
					if(item.children && item){
						this.toObj(item.children)
					}
				})
			},
			handleDept(e){
				const selects = e.detail.value
				if(selects.length){
					const selectLast = selects[selects.length - 1]
					this.$emit('change',this.deptValue,this.deptObj[selectLast.value])
				}else{
					this.$emit('change','',{})
				}
			}
		},
		mounted(){
			this.initData()
		},
		model: {
			prop: 'value',
			event: 'change'
		}
	}
</script>

<style lang="scss" scoped>
	.dept-warp{
		width: 100%;
	}
	.disabled{
		background-color: rgb(245, 247, 250);
	}
</style>